const data = require('./data.json');
const path = require('path');
const fs = require('fs');

let maxid = () => {
    let arr = [];
    data.forEach(item => {
        arr.push(item.id);
    });
    return Math.max.apply(null, arr)
}
let writeDataToFile = (res) => {
    fs.writeFile(path.join(__dirname, 'data.json'), JSON.stringify(data, null, 4), err => {
        if (err) {
            res.json({
                status: 500
            });
        }
        res.json({
            status: 200
        })
    })
}

exports.checkName = (req, res) => {
    let name = req.params.name;
    let flag = false;
    data.some(item => {
        if (name == item.name) {
            flag = true;
            return true;
        }
    })
    if (flag) {
        res.json({
            status: 1
        })
    } else {
        res.json({
            status: 2
        })
    }
}

exports.showAll = (req, res) => {
    res.json(data);
};
exports.addData = (req, res) => {
    let info = req.body;
    let book = {};
    for (let key in info) {
        book[key] = info[key];
    }
    book.date = 2525609975000;
    book.id = maxid() + 1;
    data.push(book);
    writeDataToFile(res);
};

exports.toEditBook = (req, res) => {
    let id = req.params.id;
    let book = {};
    data.some(item => {
        if (id == item.id) {
            book = item;
            return true;
        }
    });
    res.json(book);
};
exports.editBook = (req, res) => {
    let info = req.body;
    console.log(info);
    info.id = req.params.id;
    data.some(item => {
        if (info.id == item.id) {
            for (let key in info) {
                item[key] = info[key];
            }
        }
    })
    writeDataToFile(res);
}
exports.deleteBook = (req, res) => {
    let id = req.params.id;
    // console.log(id);
    data.some((item, index) => {
        if (id == item.id) {
            data.splice(index, 1);
            return true;
        }
    })
    writeDataToFile(res);
}